<?php
declare(strict_types=1);

namespace SixShop\AliyunWuliu;

use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use function SixShop\Core\throw_logic_exception;

class WuLiuClient
{

    private const string GATEWAY = 'https://wuliu.market.alicloudapi.com/';

    private HttpClientInterface $httpClient;

    public function __construct(private Config $config)
    {
        $this->httpClient = HttpClient::create([
            'base_uri' => self::GATEWAY,
            'headers' => [
                'Authorization' => 'APPCODE ' . $this->config->app_code,
            ]
        ]);
    }

    /**
     * 获取物流信息
     * @param string $no 快递单号 快递单号 【顺丰和丰网、中通等请输入单号 : 收件人或寄件人手机号后四位。例如：123456789:1234】
     * @param string $type 快递公司编码
     */
    public function kdi(string $no, string $type = ''): object
    {
        $response = $this->httpClient->request('GET', 'kdi', [
            'query' => [
                'no' => $no,
                'type' => $type,
            ]
        ]);
        $result = json_decode($response->getContent());
        if ($result->status == 0) {
            return $result->result;
        } else {
            // 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制，错误单号
            throw_logic_exception($result->msg);
        }
    }

    /**
     * 获取快递公司列表
     */
    public function getExpressList(): object
    {
        $response = $this->httpClient->request('GET', 'getExpressList');
        $result = json_decode($response->getContent());
        if ($result->status == 200) {
            return $result->result;
        } else {
            throw_logic_exception($result->msg);
        }
    }
}